import { constantRoutes } from '@/router/localRouter'
import routeMap from '@/router/dynamicConfig/index'
import Layout from '@/components/layout/index.vue'
import Iframe from '@/components/layout/Iframe/main.vue'
import itemMain from '@/components/layout/Iframe/itemMain.vue'
import util from '@/libs/util.js'
const state = {
    routes: [],
    addRoutes: [],
    addRoutesP: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes[0]
        state.routes = constantRoutes.concat(routes[0])
        state.addRoutesP = routes[1]
    }
}

/**
 * 去掉URL带的参数
 * @param url
 */
function handleUrlToName(url) {
    if (url) {
        return '/' + (url.includes('?') ? url.split('?')[0] : url)
    }
    return ''
}
/**
 * 将平级数据构建成树级菜单，用于界面菜单展示
 * @param {*} arr 数据源
 * @param {*} menuId 顶级menuId
 * @param {*} key 递归子级时用的键
 */
function makeMenu(arr, id = 0, key = 'parentId') {
    return arr
        .filter((item) => item[key] === id)
        .map((item) => ({
            ...item,
            meta: {
                title: item.nameCn,
                isIframe: item.urlType === 2,
                icon: item.icon
            },
            hidden: item.menuType === 0,
            children: makeMenu(arr, item.id)
        }))
}

/**
 * 构建出一个路由表数据
 * @param {*} arr 数据源
 * @param {*} menuId 顶级menuId
 * @param {*} key 递归子级时用的键
 */
function makeRouter(arr, id = 0, key = 'parentId') {
    // let a = sessionStorage.getItem('loginUserInfo')
    // const sysType = JSON.parse(crypto.decrypt(sessionStorage.getItem('loginUserInfo')))
    return arr
        .filter((item) => item[key] === id)
        .map((item) => {
            let isIframe = item.parentId !== 0 && item.urlType === 2
            let a = {
                ...item,
                meta: {
                    title: item.nameCn,
                    isIframe,
                    icon: item.imageUrl
                },
                path: isIframe ? '/' + item.nameEn : handleUrlToName(item.url),
                name: item.nameEn,
                children: makeRouter(arr, item.id),
                component: item.parentId === 0 ? Layout : isIframe ? Iframe : routeMap.get(item.nameEn)
                // component: item.parentId === 0 ? ((sysType && sysType.systemStyleType && sysType.systemStyleType === 1) ? Layout : navLayout) : isIframe ? Iframe : routeMap.get(item.nameEn)
            }
            // 解决多层嵌套路由问题
            if (!a.component && item.parentId !== 0 && a.children.length > 0) {
                a.component = itemMain
            }
            return a
            /* return {
            ...item,
            meta: {
                title: item.nameCn,
                isIframe,
                icon: item.imageUrl
            },
            path: isIframe ? '/' + item.nameEn : handleUrlToName(item.url),
            name: item.nameEn,
            children: makeRouter(arr, item.id),
            component: item.parentId === 0 ? Layout : isIframe ? Iframe : (item.id === 96 ? itemMain : routeMap.get(item.nameEn))
            // component: item.parentId === 0 ? ((sysType && sysType.systemStyleType && sysType.systemStyleType === 1) ? Layout : navLayout) : isIframe ? Iframe : routeMap.get(item.nameEn)
        } */
        })
}
const actions = {
    generateRoutes({ commit }) {
        return new Promise((resolve) => {
            // 路由表
            let routerTableList = []
            // 菜单路由
            let menuList = []
            util.ajaxPostData('/portal-service/api/menu/findMenuTree', {}).then((res) => {
                // util.ajaxPostData('/oss-gateway/portal-service/api/menu/findMenuTree', {}).then((res) => {
                if (res.body) {
                    // 路由表  这里有个坑必须要赋值后才能递归 很奇怪
                    routerTableList = res.body
                    // 菜单路由
                    menuList = makeMenu(routerTableList)
                    sessionStorage.setItem('isFresh', true)

                    // 路由表
                    let allRouterTableList = []
                    let permissionRouter = []
                    util.ajaxPostData('/portal-service/api/menu/findAllMenuTree', {}).then((res) => {
                        // util.ajaxPostData('/oss-gateway/portal-service/api/menu/findAllMenuTree', {}).then((res) => {
                        if (res.body) {
                            allRouterTableList = res.body
                            // 菜单路由
                            // let allMenuList = []
                            // allMenuList = makeMenu(allRouterTableList)

                            for (const item of allRouterTableList) {
                                item.isPermission = false
                            }
                            for (let i in routerTableList) {
                                for (let j in allRouterTableList) {
                                    if (routerTableList[i].id === allRouterTableList[j].id) {
                                        allRouterTableList[j].isPermission = true
                                    }
                                }
                            }
                            permissionRouter = makeRouter(allRouterTableList)
                            // 解决只有一个根节点跳转问题
                            for (let i = 0; i < permissionRouter.length; i++) {
                                let item = permissionRouter[i]
                                if (!item.children) {
                                    item.children = []
                                }
                                if (item.children <= 0) {
                                    let isIframe = item.url && item.url.includes('http')
                                    if (isIframe) {
                                        let r = {
                                            path: '/iframe',
                                            query: { src: item.url }
                                        }
                                        permissionRouter[i]['redirect'] = r
                                        let c = {
                                            meta: {
                                                title: item.nameCn,
                                                isIframe,
                                                icon: item.imageUrl
                                            },
                                            path: '/iframes',
                                            name: item.nameEn,
                                            component: Iframe
                                        }
                                        permissionRouter[i].children.push(c)
                                    }
                                }
                            }

                            let datas = []
                            datas.push(permissionRouter)
                            datas.push(menuList)
                            commit('SET_ROUTES', datas)
                            resolve(permissionRouter)
                        }
                    })
                }
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
